using System.IO;
using System;
using System.Collections.Generic;

namespace Client
{
	public class ScanDirectory
	{
		private int m_NbFolderSCanned;
		private ScanDirectory m_Parent;
		private string m_CurentPath;
		
		public string CurentPath {
			get {return m_CurentPath;}
		}
		
		public int NbFolderSCanned{
			get{return m_NbFolderSCanned;}
		}
		
		public ScanDirectory (string path){
			m_CurentPath = path;
			m_NbFolderSCanned = 0;
			m_Parent = null;
		}
		
		public ScanDirectory (string path, ScanDirectory parent){
			m_CurentPath = path;
			m_Parent = parent;
		}
		
		public List<Music> Run() {
			return GenerateList();	
		}
		
		private List<Music> GenerateList() {
			List<Music> musics = new List<Music>();
			System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(m_CurentPath);

			foreach(FileInfo dirInf in dir.GetFiles("*.mp3")) {
				Music music;
				
				try {
					musics.Add(new Music(dirInf));
				}
				catch {
					System.Console.WriteLine("Music non lisible");
				}
			}
			
			// Scan others directories
			IncrementNbFolder();
			UpdateCurrentPath();
			foreach(DirectoryInfo dirInf in dir.GetDirectories()) {
				
				try {
					ScanDirectory sd = new ScanDirectory(dirInf.FullName, this);	
					List<Music> tmpMusics = sd.Run();
					
					if(tmpMusics.Count > 0)
						musics.AddRange(tmpMusics);
				}
				catch {
					System.Console.WriteLine("Fichier non lisible : " + dirInf.FullName);
				}
			}
			
			return musics;
		}
		
		private void IncrementNbFolder() {
			if(m_Parent == null)
				m_NbFolderSCanned += 1;
			else
				m_Parent.IncrementNbFolder();
		}
		
		private void UpdateCurrentPath() {
			if(m_Parent != null)
				UpdateCurrentPath(m_CurentPath);
		}
		
		private void UpdateCurrentPath(string path) {
			if(m_Parent == null)
				m_CurentPath = path;
			else
				m_Parent.UpdateCurrentPath(path);
		}
	}
}

